<script setup lang="ts">
import {reactive, ref} from "vue";
import type {ElForm} from "element-plus";
import {ElMessage} from "element-plus";
import {addAccount} from "../../api/user";
import {checkaccount, checkpassword} from "../../utils/utils";
import {useRouter} from "vue-router";

const accountForms = ref<InstanceType<typeof ElForm>>()
const router = useRouter()
const accountForm = reactive({
  account: '',
  password: '',
  userGroup: ''
})
const rules = reactive({
  account: [{validator: checkaccount, trigger: 'blur'}],
  password: [{validator: checkpassword, trigger: 'blur'}],
  userGroup: [{required: true, message: '请输入账号', trigger: 'change'}]
})

function accountAddto(accountForms: InstanceType<typeof ElForm>) {
  accountForms.validate(async (valid: any) => {
    if (valid) {
      let res = await addAccount({...accountForm})
      let {code, msg} = res.data
      if (code == 0) await router.push('/account')
      else ElMessage({message: '验证失败', type: 'error'})
    }
  })
}

function accountReset(accountForms: InstanceType<typeof ElForm>) {
  accountForms.resetFields()
}
</script>
<template>
  <div class="accountadd">
    <div class="header">添加账号</div>
    <div class="main">
      <el-form
          ref="accountForms"
          :rules="rules"
          :model="accountForm"
          label-width="70px"
          size="mini"
      >
        <!-- 账号 -->
        <el-form-item prop="account" label="账号">
          <el-input v-model="accountForm.account"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password" label="密码">
          <el-input type="password" v-model="accountForm.password"></el-input>
        </el-form-item>
        <!-- 用户组 -->
        <el-form-item prop="userGroup" label="用户组">
          <el-select v-model="accountForm.userGroup" placeholder="请选择用户组">
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="普通管理员" value="普通管理员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 添加 -->
      <div class="btn">
        <el-button size="small" type="primary" @click="accountAddto(accountForms)"
        >添加
        </el-button>
        <!-- 重置 -->
        <el-button size="small" @click="accountReset(accountForms)">重置</el-button>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.header {
  line-height: 50px;
  padding-left: 10px;
  box-sizing: border-box;
  border-bottom: 1px solid #eee;
}

:deep(.el-input--suffix .el-input__inner) {
  width: 250px;
}

.main {
  margin-top: 20px;
  padding-left: 30px;
  padding-bottom: 30px;
  width: 350px;

  .btn {
    width: 350px;
    display: flex;
    justify-content: center;
  }
}

</style>
